package cn.ubest.mvvmcore.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;

import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.core.content.ContextCompat;

import java.io.InputStream;

import cn.ubest.mvvmcore.BaseApplication;

/**
 * Created by maoqi on 2020/3/10.
 */
public class ResourcesUtils {
    private ResourcesUtils() {
    }

    public static Resources getResources() {
        return BaseApplication.application.getResources();
    }

    /**
     * 获取文字
     */
    public static String getString(int resId) {
        return getResources().getString(resId);
    }

    /**
     * 获取dimen
     */
    public static int getDimens(@DimenRes int resId) {
        return getResources().getDimensionPixelSize(resId);
    }

    /**
     * 获取颜色
     */

    public static int getColor(@ColorRes int resId) {
        return ContextCompat.getColor(BaseApplication.application, resId);
    }

    /**
     * 获取颜色
     */

    public static int getColor(String color) {
        return Color.parseColor(color);
    }

    /**
     * 获取assets中的String
     *
     * @param context
     * @param path
     * @return
     * @throws Exception
     */
    public static String getAssetsString(Context context, String path) {
        try {
            InputStream is = context.getAssets().open(path);
            int lenght = is.available();
            byte[] buffer = new byte[lenght];
            is.read(buffer);
            return new String(buffer, "gbk");
        } catch (Exception e) {

        }

        return "";
    }

    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dp(final float pxValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(final float spValue) {
        final float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2sp(final float pxValue) {
        final float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }
}
